package com.bitter.storage.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bitter.storage.StorageException;
import com.bitter.storage.domain.StorageVo;
import com.bitter.storage.mapper.StorageMapper;

@Service
public class StorageService implements IStorageService {

	private static Logger log = LoggerFactory.getLogger(StorageService.class);

	@Autowired
	StorageMapper storageMapper;

	public String decrease(Long productId, Integer total) {
		StorageVo storageVo = new StorageVo();
		storageVo.setProductId(productId);
		int org_total = getTotal(productId);
		log.info("########现有的库存数据为：{}########", org_total);
		storageVo.setTotal((getTotal(productId) - total));
		UpdateWrapper<StorageVo> updateWrapper = new UpdateWrapper<>();
		updateWrapper.lambda().eq(StorageVo::getProductId, productId);
		log.info("########进入更新库存开始########");
		storageMapper.update(storageVo, updateWrapper);
		log.info("########进入更新库存结束########");
		return "decrease";

	}

	void validateTotal(Integer total, Integer org_total) throws StorageException {
		if (total >= org_total) {
			throw new StorageException("对不起，订单无法完成,原因库存不足");
		}
	}

	public Integer getTotal(Long productId) {
		StorageVo st = storageMapper
				.selectOne(new QueryWrapper<StorageVo>().lambda().eq(StorageVo::getProductId, productId));
		return st.getTotal();
	}

}
